package com.example.recorder;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import java.util.Vector;

/**
 * @author hdz
 * @date 2023/12/13 14:52
 */
public class VisualizerView extends View {

    private Paint paint;
    private Vector<short[]> data;

    public VisualizerView(Context context) {
        super(context);
        init();
    }

    public VisualizerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public VisualizerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setColor(getResources().getColor(android.R.color.holo_blue_bright));
        paint.setStrokeWidth(3.0f);

        data = new Vector<>(320);
    }

    public void updateVisualizer(byte[] audioData, int length) {
        this.updateVisualizer(bytesToShorts(audioData, length));
    }

    public void updateVisualizer(short[] audioData) {
        data.add(audioData);
        postInvalidate();  // Trigger a redraw
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (data.size() <= 0) {
            return;
        }
        short[] audioData = data.remove(0);

        int width = getWidth();
        int height = getHeight();

        float centerY = height / 2.0f;
        float scaleX = (float) width / (float) audioData.length;

        if (true) {
            int barWidth = width / audioData.length;
            for (int i = 0; i < audioData.length; i++) {
                float barHeight = Math.abs(audioData[i] / 32768.0f) * height;
                float left = i * barWidth;
                float top = height - barHeight;
                float right = left + barWidth;
                float bottom = height;

                canvas.drawRect(left, top, right, bottom, paint);
            }
        } else {
            for (int i = 0; i < audioData.length - 1; i++) {
                float x1 = i * scaleX;
                float y1 = centerY - (audioData[i] / 32768.0f) * centerY;

                float x2 = (i + 1) * scaleX;
                float y2 = centerY - (audioData[i + 1] / 32768.0f) * centerY;

                canvas.drawLine(x1, y1, x2, y2, paint);
            }
        }
    }


    private short[] bytesToShorts(byte[] bytes, int length) {
        if (bytes == null || length % 2 != 0) {
            throw new IllegalArgumentException("Invalid byte array");
        }

        short[] shorts = new short[length / 2];
        for (int i = 0, j = 0; i < length; i += 2, j++) {
            // 将两个字节合并为一个short
            shorts[j] = (short) ((bytes[i] & 0xFF) | (bytes[i + 1] << 8));
        }

        return shorts;
    }
}

